package com.cyanite.playlv2;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cyanite.playlv2.util.StringFormatters;
import com.cyanite.playlv2.util.TipUtils;
import com.cyanite.playlv2api.types.Tip;
import com.cyanite.playlv2api.types.Venue;
import com.cyanite.playlv2.R;

/**
 * Shows actions a user can perform on a tip, which includes marking a tip
 * as a to-do, marking a tip as done, un-marking a tip. Marking a tip as
 * a to-do will generate a to-do, which has the tip as a child object.
 *
 * The intent will return a Tip object and a Todo object (if the final state
 * of the tip was marked as a Todo). In the case where a Todo is returned,
 * the Tip will be the representation as found within the Todo object.
 *
 * If the user does not modify the tip, no intent data is returned. If the
 * final state of the tip was not marked as a to-do, the Todo object is
 * not returned.
 *
 *
 */
public class TipActivity extends Activity {

    public static final String EXTRA_TIP_PARCEL = PlayLv2.PACKAGE_NAME
        + ".TipActivity.EXTRA_TIP_PARCEL";
    public static final String EXTRA_VENUE_CLICKABLE = PlayLv2.PACKAGE_NAME
        + ".TipActivity.EXTRA_VENUE_CLICKABLE";

    /**
     * Always returned if the user modifies the tip in any way. Captures the
     * new <status> attribute of the tip. It may not have been changed by the
     * user.
     */
    public static final String EXTRA_TIP_RETURNED = PlayLv2.PACKAGE_NAME
        + ".TipActivity.EXTRA_TIP_RETURNED";

    /**
     * If the user marks the tip as to-do as the final state, then a to-do object
     * will also be returned here. The to-do object has the same tip object as
     * returned in EXTRA_TIP_PARCEL_RETURNED as a child member.
     */
    public static final String EXTRA_TODO_RETURNED = PlayLv2.PACKAGE_NAME
        + ".TipActivity.EXTRA_TODO_RETURNED";

    private StateHolder mStateHolder;
    private ProgressDialog mDlgProgress;


    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tip_activity);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));

        mStateHolder = new StateHolder();
        if (getIntent().getExtras() != null) {
        	if (getIntent().hasExtra(EXTRA_TIP_PARCEL)) {
        		Tip tip = getIntent().getExtras().getParcelable(EXTRA_TIP_PARCEL);
        		mStateHolder.setTip(tip);
        	} else {
                finish();
                return;
        	}

            if (getIntent().hasExtra(EXTRA_VENUE_CLICKABLE)) {
            	mStateHolder.setVenueClickable(
            			getIntent().getBooleanExtra(EXTRA_VENUE_CLICKABLE, true));
            }
        } else {
            finish();
            return;
        }

        ensureUi();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mStateHolder.getIsRunningTipTask()) {
            startProgressBar();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if (isFinishing()) {
            stopProgressBar();
        }
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    private void ensureUi() {
        Tip tip = mStateHolder.getTip();
        Venue venue = tip.getVenue();

        LinearLayout llHeader = (LinearLayout)findViewById(R.id.tipActivityHeaderView);
        if (mStateHolder.getVenueClickable()) {
	        llHeader.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                showVenueDetailsActivity(mStateHolder.getTip().getVenue());
	            }
	        });
        }

        ImageView ivVenueChevron = (ImageView)findViewById(R.id.tipActivityVenueChevron);
        if (mStateHolder.getVenueClickable()) {
        	ivVenueChevron.setVisibility(View.VISIBLE);
        } else {
        	ivVenueChevron.setVisibility(View.INVISIBLE);
        }

        TextView tvTitle = (TextView)findViewById(R.id.tipActivityName);
        TextView tvAddress = (TextView)findViewById(R.id.tipActivityAddress);
        if (venue != null) {
	        tvTitle.setText(venue.getName());

	        tvAddress.setText(
	            venue.getAddress() +
	            (TextUtils.isEmpty(venue.getCrossstreet()) ?
	                    "" : " (" + venue.getCrossstreet() + ")"));
        } else {
        	tvTitle.setText("");
        	tvAddress.setText("");
        }

        TextView tvBody = (TextView)findViewById(R.id.tipActivityBody);
        tvBody.setText(tip.getShout());

        String created = getResources().getString(
                R.string.tip_activity_created,
                StringFormatters.getTipAge(getResources(), tip.getPostDate()));
        TextView tvDate = (TextView)findViewById(R.id.tipActivityDate);
        tvDate.setText(created);

        TextView tvAuthor = (TextView)findViewById(R.id.tipActivityAuthor);
        if (tip.getUserName() != null) {
            tvAuthor.setText(tip.getUserName());
            tvAuthor.setClickable(true);
            tvAuthor.setFocusable(true);
            tvAuthor.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showUserDetailsActivity(mStateHolder.getTip().getUserId());
                }
            });

            tvDate.setText(tvDate.getText() + getResources().getString(
                    R.string.tip_activity_created_by));
        } else {
            tvAuthor.setText("");
        }

        updateButtonStates();
    }

    private void updateButtonStates() {
        Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList);
        Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis);
        TextView tv = (TextView)findViewById(R.id.tipActivityCongrats);
        Tip tip = mStateHolder.getTip();

        if (TipUtils.isTodo(tip)) {
            btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_1)); // "REMOVE FROM MY TO-DO LIST"
            btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
            btn1.setVisibility(View.VISIBLE);
            tv.setVisibility(View.GONE);
        } else if (TipUtils.isDone(tip)) {
            tv.setText(getResources().getString(R.string.tip_activity_btn_tip_4));   // "CONGRATS! YOU'VE DONE THIS"
            btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_3)); // "UNDO THIS"
            btn1.setVisibility(View.GONE);
            tv.setVisibility(View.VISIBLE);
        } else {
            btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_0)); // "ADD TO MY TO-DO LIST"
            btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
            btn1.setVisibility(View.VISIBLE);
            tv.setVisibility(View.GONE);
        }
    }

    private void showUserDetailsActivity(String userId) {
        Intent intent = new Intent(this, UserDetailsActivity.class);
        intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId);
        startActivity(intent);
    }

    private void showVenueDetailsActivity(Venue venue) {
        Intent intent = new Intent(this, VenueActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
        startActivity(intent);
    }

    private void startProgressBar() {
        if (mDlgProgress == null) {
            mDlgProgress = ProgressDialog.show(this, "",
                    getResources().getString(R.string.tip_activity_progress_message));
        }
        mDlgProgress.show();
    }

    private void stopProgressBar() {
        if (mDlgProgress != null) {
            mDlgProgress.dismiss();
            mDlgProgress = null;
        }
    }

    private static class StateHolder {
        private Tip mTip;
        private boolean mIsRunningTipTask;
        private boolean mVenueClickable;
       
        public StateHolder() {
        	mTip = null;
            mIsRunningTipTask = false;
            mVenueClickable = true;
        }

        public Tip getTip() {
        	return mTip;
        }

        public void setTip(Tip tip) {
        	mTip = tip;
        }

        public boolean getIsRunningTipTask() {
            return mIsRunningTipTask;
        }

        public boolean getVenueClickable() {
        	return mVenueClickable;
        }

        public void setVenueClickable(boolean venueClickable) {
        	mVenueClickable = venueClickable;
        }
    }
}
